import React, { memo, useEffect, useRef, useState } from "react";
import { Rnd } from "react-rnd";
import './style.less'
import { Divider, Spin } from "antd";
import useDesignerStore from "@/store/Designer";
import { CaretDownOutlined, CaretUpOutlined } from "@ant-design/icons";
import { DRAWER_INIT_HEIGHT } from "@/constant/config";
import { DataSource } from './DataSource'
import { useCurrentNode } from "@/hooks/useCurrentNode";
import { AggregateNode, JoinNode, UnionNode, PersistNode, SinkNode, SqlNode, TransposeNode, PreprocessNode } from "../CustomNode";
import { DataTransform } from "./DataTransform";
import { DataSink } from "./DataSink";
import { debounce } from "lodash-es";
import { DataPreprocess } from "./DataPreprocess";
import { motion } from 'motion/react'

const DrawerContent = memo(() => {
  const { drawerBottomArrow, toggleDrawerArrow,
    setShouldDrawerUpdate, drawerHeight } = useDesignerStore()
  const currentNode = useCurrentNode()

  const handleClick = () => {
    toggleDrawerArrow()
    setShouldDrawerUpdate(true)
  }

  const renderContent = () => {
    if (!currentNode?.type) {
      return null
    } else if ([SqlNode.displayName].includes(currentNode?.type)) {
      return <DataSource />
    } else if ([PreprocessNode.displayName].includes(currentNode?.type)) {
      return <DataPreprocess />
    } else if ([TransposeNode.displayName, UnionNode.displayName,
    AggregateNode.displayName, JoinNode.displayName].includes(currentNode?.type)) {
      return <DataTransform />
    } else if ([SinkNode.displayName, PersistNode.displayName].includes(currentNode?.type)) {
      return <DataSink />
    }
  }

  return <div className="drawer-content">
    <motion.div
      style={{
        position: "absolute",
        left: '50%',
        top: -12,
        cursor: 'pointer',
        width: 150,
        height: 10,
        background: '#fff',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        borderTopLeftRadius: 8,
        borderTopRightRadius: 8,
        border: 'solid 1px #ccc',
        borderBottom: 'none',
        transform: 'translateX(-50%)',
        zIndex: 1001
      }}
      onClick={handleClick}
      initial={{ scale: 1 }}
      whileHover={{ scale: 1.1 }}
      whileTap={{ scale: 0.95 }}
    >
      {drawerBottomArrow === 'down' ? <CaretDownOutlined /> : <CaretUpOutlined />}
    </motion.div>
    <div className="drawer-content-top">
      <div className="content-title">
        {currentNode?.data?.label}
      </div>
      <Divider style={{ margin: '0 0 12px' }} />
    </div>
    <div style={{ height: drawerHeight - 65 }}>
      {
        renderContent()
      }
    </div>

  </div>
})

const PropertyPanelContainer = memo(({ children }) => {
  const { drawerBottomArrow, shouldDrawerUpdate,
    setShouldDrawerUpdate, setDrawerArrow,
    drawerHeight, setDrawerHeight
  } = useDesignerStore()
  const initHeight = useRef(0); // 用于记录调整的初始值

  useEffect(() => {
    if (!shouldDrawerUpdate) return
    const height = drawerBottomArrow === 'up' ?  DRAWER_INIT_HEIGHT : window.innerHeight - 15
    setDrawerHeight(height)
    setShouldDrawerUpdate(false)
  }, [shouldDrawerUpdate])

  useEffect(() => {
    const onResize = debounce(() => {
      initHeight.current = drawerHeight
      handleResize(null, null, null, { width: 0, height: 0 }, null)
    }, 150)
    window.addEventListener('resize', onResize)
    return () => {
      window.removeEventListener('resize', onResize)
    }
  }, [])

  const handleResize = (e, dir, elementRef, delta, pos) => {
    // 基于初始值和 delta 计算新的宽度和高度
    // const newWidth = initHeight.current.width + delta.width;
    const newHeight = initHeight.current + delta.height;
    if (newHeight >= window.innerHeight / 2) {
      setDrawerArrow('down')
    }
    else {
      setDrawerArrow('up')
    }
    setDrawerHeight(newHeight)
  }
  const handleResizeStart = () => {
    // 记录调整的初始值
    initHeight.current = drawerHeight
  };

  return (
    <div className="drawer-bottom">
      <Rnd
        size={{
          width: '100%',
          height: drawerHeight
        }}
        onResize={handleResize}
        onResizeStart={handleResizeStart}
        position={{
          x: 0,
          y: window.innerHeight - drawerHeight
        }}
        enableResizing={{
          top: true, // 允许从顶部调整高度
        }}
        disableDragging // 禁止拖动
        // bounds="parent" // 限制在父容器内
        // minHeight={DRAWER_INIT_HEIGHT} // 最小高度
        // maxHeight={window.innerHeight - 50} // 最大高度
        className="drawer-bottom-rnd"
        resizeHandleWrapperClass="horizon-rnd-wrapper"
      >
        {
          children
        }
      </Rnd>
    </div>
  );
})

const PropertyPanel = () => {
  const currentNode = useCurrentNode()
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    setLoading(true)
    setTimeout(() => {
      setLoading(false)
    }, 200)
  }, [currentNode])

  if (!currentNode) {
    return null
  }

  return <PropertyPanelContainer>
    <Spin spinning={loading}>
      <DrawerContent />
    </Spin>
  </PropertyPanelContainer>
}

export default PropertyPanel